package com.cm.root;

import android.annotation.TargetApi;
import android.os.Build;
import android.text.TextUtils;

import com.ijinshan.rt.common.IRootKeeper;

import java.io.File;

public class SuExec {
    public static final int ERROR_CHECK_ROOT_FAILED = -1000;
    private static SuExec mInstance = new SuExec();
    private Thread mThreadGetSu = null;
    private IRootKeeper mRootKeeper = null;

    private SuExec() {
    }

    public static synchronized SuExec getInstance() {
        return mInstance;
    }


    // 判断手机是否被ROOT

    public boolean isMobileRoot() {

        String rootpath = xGetCmdPath("su");
        if (null != rootpath) {

            boolean isSuBinExecutive = isSuBinExecutive(rootpath);
            if (isSuBinExecutive) {
               // TODO check 小米
                return true;
            } else {
                return false;
            }
        }

        return false;
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    private boolean isSuBinExecutive(String suBin) {

        if (!TextUtils.isEmpty(suBin)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                File file = new File(suBin);
                if (null == file)
                    return false;
                boolean canExecute = file.canExecute();
                return canExecute;
            } else
                return true;
        } else {
            return false;
        }
    }
    private static final String[] bin_dirs = { "/system/sbin/",
            "/system/xbin/", "/system/bin/" };

    private String xGetCmdPath(String cmd) {

        if (cmd.indexOf('/') != -1) {
            return cmd;
        }
        for (int i = 0; i < bin_dirs.length; i++) {
            try {
                String path = bin_dirs[i] + cmd;
                if (new File(path).exists()) {
                    return path;
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return null;
    }

}
